package com.gcloud.mesh.dcs.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.entity.IaasEntity;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.enums.DeviceThresholdType;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.monitor.service.StatisticsService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ServerPowerThreholdService implements IDeviceThresholdService {

	@Autowired
	private AppDao appDao;

	@Autowired
	private IaasDao iaasDao;

	@Autowired
	private StatisticsService statisticsService;

	@Autowired
	private StatisticsCheatService statisticsCheatService;

	@Override
	public DeviceThresholdType device() {
		return DeviceThresholdType.SERVER_POWER;
	}

	@Override
	public Boolean checkScheduler(String datacenterId,String operation, Double value) {

		Map<String, Object> props = new HashMap<>();
		// props.put("datacenter_id", app.getDatacenterId());
		props.put("type", DeviceType.SERVER.getNo());
		List<IaasEntity> iaases = iaasDao.findByProperties(props);
		if (iaases != null) {
			for (IaasEntity iaas : iaases) {
				String powerStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_POWER.getMeter(), iaas.getId());
				log.info("监控项[SERVER_POWER] id:{}, value:{}", iaas.getId(), powerStr);
				if (powerStr.length() <= 0) {
					continue;
				}
				Double power = Double.parseDouble(powerStr);
				if ("<".equals(operation)) {
					if (power < value) {
						return true;
					}
				} else if (">".equals(operation)) {
					if (power > value) {
						return true;
					}
				} else if ("=".equals(operation)) {
					if (power == value) {
						return true;
					}
				} else if ("<=".equals(operation)) {
					if (power <= value) {
						return true;
					}
				} else if (">=".equals(operation)) {
					if (power >= value) {
						return true;
					}
				} else if ("!=".equals(operation)) {
					if (power != value) {
						return true;
					}
				} else{
					return false;
				}

			}
		}
		return false;
	}

}
